package controllers

import (
    "bankend/models"
    "bankend/services"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
)

var userSubscribeService = new(services.UserSubscribeService)

// GetUserSubscribe 获取用户订阅设置
// GET /api/user-subscribes/:user_id
func GetUserSubscribe(c *gin.Context) {
    userID, err := strconv.Atoi(c.Param("user_id"))
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
        return
    }

    subscribe, err := userSubscribeService.GetUserSubscribe(userID)
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": "订阅设置不存在"})
        return
    }

    c.JSON(http.StatusOK, gin.H{"subscribe": subscribe})
}

// CreateUserSubscribe 创建用户订阅设置
// POST /api/user-subscribes
func CreateUserSubscribe(c *gin.Context) {
    var subscribe models.UserSubscribe
    if err := c.ShouldBindJSON(&subscribe); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := userSubscribeService.CreateUserSubscribe(&subscribe); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusCreated, gin.H{"subscribe": subscribe})
}

// UpdateUserSubscribe 更新用户订阅设置
// PUT /api/user-subscribes/:user_id
func UpdateUserSubscribe(c *gin.Context) {
    userID, err := strconv.Atoi(c.Param("user_id"))
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
        return
    }

    var subscribe models.UserSubscribe
    if err := c.ShouldBindJSON(&subscribe); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    subscribe.UserID = userID
    if err := userSubscribeService.UpdateUserSubscribe(&subscribe); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"subscribe": subscribe})
}

// DeleteUserSubscribe 删除用户订阅设置
// DELETE /api/user-subscribes/:user_id
func DeleteUserSubscribe(c *gin.Context) {
    userID, err := strconv.Atoi(c.Param("user_id"))
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
        return
    }

    if err := userSubscribeService.DeleteUserSubscribe(userID); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "订阅设置已删除"})
}